<?php

/*
 * Edit by xinli
 * Click nbfs://nbhost/SystemFileSystem/Templates/Scripting/PHPClass.php to edit this template
 */

namespace api\mall\controller;

use think\facade\Log;
use cmf\controller\RestBaseController;
use app\portal\model\UserRealNameInfoModel;
use api\portal\service\UserInfoService;

/**
 * @OA\Tag(
 *     name="mall-baidu-ocr",
 *     description="百度OCR"
 * )
 */
class BaiduOcrController extends RestBaseController
{
    // const API_KEY = "h6wbX09mGnFm8JrEepbAZp3g";
    // const SECRET_KEY = "PhUtFRGrlG1GkgzJhpl3j8t9rPBbLqah";
    const API_KEY = "iDYjEwZA3Oqqe7wz5QpCalvr";
    const SECRET_KEY = "fKxNKEwAnzE9L5OFT4kC8voLy12hQyZb";

    protected function initialize()
    {
        parent::initialize();
        if (empty($this->user)) {
            $this->error('login');
        }
    }

    /**
     * 使用 AK，SK 生成鉴权签名（Access Token）
     * @return string 鉴权签名信息（Access Token）
     */
    private function getAccessToken(){
        $curl = curl_init();
        $postData = array(
            'grant_type' => 'client_credentials',
            'client_id' => self::API_KEY,
            'client_secret' => self::SECRET_KEY
        );
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'https://aip.baidubce.com/oauth/2.0/token',
            CURLOPT_CUSTOMREQUEST => 'POST',
            CURLOPT_SSL_VERIFYPEER  => false,
            CURLOPT_SSL_VERIFYHOST  => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POSTFIELDS => http_build_query($postData)
        ));
        $response = curl_exec($curl);
        curl_close($curl);
        $rtn = json_decode($response);
        return $rtn->access_token;
    }

    // /**
    //  * Swagger测试
    //  * @throws \think\exception\DbException
    //  * @OA\Get(
    //  *     tags={"mall-baidu-ocr"},
    //  *     path="/mall/baiduOcr/test",
    //  *     @OA\Response(response=200, ref="#/components/responses/200")
    //  * )
    //  */
    // public function test() {
    //     // 实名成功后改变UserPromoteRelationModel用户状态 之后根据直推人数发放奖励并判断升级
    //     $userInfoService = new UserInfoService();
    //     $userInfoService->userPromoteRelation($this->userId);
    // }

    /**
     * 身份证识别图片转文字
     * @OA\Post(
     *     tags={"mall-baidu-ocr"},
     *     path="/mall/baiduOcr/idCardRecognition",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="file", type="file", description="正面图片")
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */
    public function idCardRecognition()
    {
        if ($this->request->isPost()) {
            if ($_FILES['file']['error'] !== UPLOAD_ERR_OK) {
                $this->error('上传出错');
            }

            $img = base64_encode(file_get_contents($_FILES['file']['tmp_name']));

            // $token = '[调用鉴权接口获取的token]';
            $url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token={$this->getAccessToken()}";
            // $img = file_get_contents('[本地文件路径]');
            // $img = base64_encode($img);
            $bodys = array(
                'id_card_side' => "front",
                'image' => $img
            );
            
            $postUrl = $url;
            $curlPost = $bodys;
            // 初始化curl
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $postUrl);
            curl_setopt($curl, CURLOPT_HEADER, 0);
            // 要求结果为字符串且输出到屏幕上
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            // post提交方式
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $curlPost);
            // 运行curl
            $res = curl_exec($curl);
            curl_close($curl);
        
            // var_dump($res);
            Log::info('[ promote ] 当前用户[' . $this->userId . '] 实名回报：' . $res); 

            $res = json_decode($res, true);
            if (empty($res)) {
                $this->error('识别失败');
            }
            $wordsResult = $res['words_result'];
            if (!isset($wordsResult['姓名']) || !isset($wordsResult['性别']) || !isset($wordsResult['民族']) || !isset($wordsResult['出生']) || !isset($wordsResult['住址']) || !isset($wordsResult['公民身份号码'])) {
                $this->error('识别失败');
            }
            
            $userRealNameInfoModel = new UserRealNameInfoModel();
            $userRealNameInfo = $userRealNameInfoModel->where('user_id', $this->userId)->find();
            if (!empty($userRealNameInfo)) {
                $this->error('已实名');
            }
            $userRealNameInfo = $userRealNameInfoModel->where('id_card_number', $wordsResult['公民身份号码']['words'])->find();
            if (!empty($userRealNameInfo)) {
                $this->error('身份证号已被实名');
            }
            
            // 更新到表cmf_user_real_name_info中
            $update = [
                'user_id' => $this->userId,
                'name' => $wordsResult['姓名']['words'],
                'sex' => $wordsResult['性别']['words'],
                'nation' => $wordsResult['民族']['words'],
                'birthday' => $wordsResult['出生']['words'],
                'address' => $wordsResult['住址']['words'],
                'id_card_number' => $wordsResult['公民身份号码']['words'],
                'create_time' => time(),
                'update_time' => time()
            ];   
            $userRealNameInfoModel->insert($update);

            // 实名成功后改变UserPromoteRelationModel用户状态 之后根据直推人数发放奖励并判断升级
            $userInfoService = new UserInfoService();
            $userInfoService->userPromoteRelation($this->userId);

            $this->success('ok', $res);
        }
    }

    /**
     * 身份证识别前端确认后提交
     * @OA\Post(
     *     tags={"mall-baidu-ocr"},
     *     path="/mall/baiduOcr/idCardRecognitionCommit",
     *     @OA\RequestBody(
     *         @OA\JsonContent(
     *             type="object",
     *             @OA\Property(property="姓名", type="string", description="姓名"),
     *             @OA\Property(property="性别", type="string", description="性别"),
     *             @OA\Property(property="民族", type="string", description="民族"),
     *             @OA\Property(property="出生", type="string", description="出生"),
     *             @OA\Property(property="住址", type="string", description="住址"),
     *             @OA\Property(property="公民身份号码", type="string", description="公民身份号码"),
     *         )
     *     ),
     *     @OA\Response(response=200, ref="#/components/responses/200")
     * )
     */    
     public function idCardRecognitionCommit()
     {
        $wordsResult = $this->request->post();
        if (empty($wordsResult)) {
            $this->error('识别失败，非法数据');
        }
        if (!isset($wordsResult['姓名']) || !isset($wordsResult['性别']) || !isset($wordsResult['民族']) || !isset($wordsResult['出生']) || !isset($wordsResult['住址']) || !isset($wordsResult['公民身份号码'])) {
            $this->error('识别失败, 缺少字段');
        }

        $userRealNameInfoModel = new UserRealNameInfoModel();
        $userRealNameInfo = $userRealNameInfoModel->where('user_id', $this->userId)->find();
        if (!empty($userRealNameInfo)) {
            $this->error('已经实名，无法更改');
        }

        // 更新到表cmf_user_real_name_info中
        $update = [
            'user_id' => $this->userId,
            'name' => $wordsResult['姓名'],
            'sex' => $wordsResult['性别'],
            'nation' => $wordsResult['民族'],
            'birthday' => $wordsResult['出生'],
            'address' => $wordsResult['住址'],
            'id_card_number' => $wordsResult['公民身份号码'],
            'create_time' => time(),
            'update_time' => time()
        ];   
        $userRealNameInfoModel->insert($update);

        // 实名成功后改变UserPromoteRelationModel用户状态 之后根据直推人数发放奖励并判断升级
        $userInfoService = new UserInfoService();
        $userInfoService->userPromoteRelation($this->userId);

        $this->success('ok');
        
    }
}
